<?php
namespace lib;

require  'DbInterface.php';
/**
* 
*/
class MysqlDb  implements  DbInterface
{
	private $db;
	private $table;
	public  $data = array();
	public  $where='';


	/*
	*实例化的过程中连接数据库
	*
	*/
	function __construct()
	{
		$config = require  CONFIG_PATH.'database.php';
		try{
			$dsn = "mysql:host={$config['host']};dbname={$config['db_name']}"; 
			$this->db = new \PDO($dsn,$config['user_name'], $config['password']);
		}catch(\PDOException $e){
			print "Error: " . $e->getMessage() . "<br/>";
    		die();
		}

	}
	/*
	获取数据
	@param array|string  $field 字段值
	@return 
	*/
	public  function  get($field = [])
	{
		if( empty($this->where) ){
			if( empty($field) ){
				$sql = "SELECT * FROM {$this->table}";
			}elseif(is_array($field)){
				$fields = implode(',', $field);
				$sql = "SELECT {$fields} FROM {$this->table}";
			}elseif(is_string($field)){
				$sql = "SELECT {$field} FROM {$this->table}";
			}else{				
				try{
					throw new \Exception("get()方法参数错误", 1);	
				}catch(\Exception $e){
					echo 'Message: ' .$e->getMessage()." in  ".$e->getFile()." in  line ".$e->getLine();
					//var_dump($e->getTrace());
					exit();
				}
			}			
			return $this->query($sql);
		}else{
			if( empty($field) ){
				$sql = "SELECT * FROM {$this->table} WHERE {$this->where}";
			}elseif(is_array($field)){
				$fields = implode(',', $field);
				$sql = "SELECT {$fields} FROM {$this->table}  WHERE {$this->where}";
			}elseif(is_string($field)){
				$sql = "SELECT {$field} FROM {$this->table} WHERE {$this->where}";
			}else{
				
				try{
					throw new \Exception("get()方法参数错误", 1);	
				}catch(\Exception $e){
					echo 'Message: ' .$e->getMessage()." in  ".$e->getFile()." in  line ".$e->getLine();
					//var_dump($e->getTrace());
					exit();
				}

			}			
			return $this->query($sql);
		}
	}
	public  function  set()
	{

	}
	/*
	*@param  string|array  $where  
	*/
	public  function  where($where)
	{
		$this->where = $this->paraseWhere($where);
	}

	/*
	*解析where子句
	*@param string|array  $where
	*/
	public function paraseWhere($where)
	{
		# code...
	}
	public  function  delete()
	{

	}
	public  function  limite()
	{

	}
	public  function  orderBy()
	{

	}
	public  function  add()
	{

	}
	public  function  first()
	{

	}
	public function groupBy($value='')
	{
		# code...
	}
	/*
	@param   string  $table  表名
	@return  object 数据库实例
	*/
	public  function  table($table)
	{	
		$this->table = $table;
		return $this;
	}

	public function  toArray()
	{

	}

	public function __get($name)
	{
		if( array_key_exists($name, $this->data) ){
			return $data[$name];
		}else{
			//throw new \Exception("{$name}不存在", 1);		
		}
	}
	/*
	@param  String  $sql sql语句
	@return obj  查询结果
	*/
	public function query ($sql)
	{
		$pre = $this->db->prepare($sql); //预处理
		$pre->execute(); //执行查询			
		$result = $pre->fetchAll(\PDO::FETCH_OBJ); //处理结果
		return $result;
		
	}
}